package pl.vanta.utils.gui.utils;

import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JComponent;
import javax.swing.TransferHandler;

public class FileTransferHandler extends TransferHandler
{
	private static final long			serialVersionUID	= 1L;

	private List<FileTransferListener>	listeners;

	private FileFilter					fileFilter;

	public FileTransferHandler()
	{
		this(null);
	}

	public FileTransferHandler(FileFilter fileFilter)
	{
		this.listeners = new ArrayList<FileTransferListener>();

		this.fileFilter = fileFilter;
	}

	@SuppressWarnings("unchecked")
	public boolean importData(JComponent comp, Transferable t)
	{
		if (!t.isDataFlavorSupported(DataFlavor.javaFileListFlavor))
		{
			return false;
		}

		try
		{
			List<File> data = (List<File>) t.getTransferData(DataFlavor.javaFileListFlavor);

			List<File> files = new ArrayList<File>();

			if (this.fileFilter != null)
			{
				for (File file : data)
				{
					if (this.fileFilter.accept(file))
					{
						files.add(file);
					}
				}
			}
			else
			{
				files.addAll(data);
			}

			for (FileTransferListener listener : this.listeners)
			{
				listener.filesImported(files);
			}

			return true;
		}
		catch (UnsupportedFlavorException ufe)
		{
			for (FileTransferListener listener : this.listeners)
			{
				listener.importError();
			}
		}
		catch (IOException ioe)
		{
			for (FileTransferListener listener : this.listeners)
			{
				listener.importError();
			}
		}

		return false;
	}

	public boolean canImport(JComponent comp, DataFlavor[] transferFlavors)
	{
		for (int i = 0; i < transferFlavors.length; i++)
		{
			if (!transferFlavors[i].equals(DataFlavor.javaFileListFlavor))
			{
				return false;
			}
		}

		return true;
	}

	public void addFileTransferListener(FileTransferListener listener)
	{
		this.listeners.add(listener);
	}

	public void removeFileTransferListener(FileTransferListener listener)
	{
		this.listeners.remove(listener);
	}
}